﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;
using Fcdbas.Core;
using Fcdbas.Core.Reflection;
using Fcdbas.Core.Configuration;
using Fcdbas.Core.Compression;
using Fcdbas.Core.DataAccess;
using Fcdbas.Platform;
using Fcdbas.DataContract;
using Fcdbas.ServiceProxy;
using Fcdbas.Biz;
namespace Fcdbas.WinUI.Common
{
    public class cSessionManager : FunctionClassBase
    {
        public static SalArray<SalString> __c_sSqlResult;
       // public SalString __sObjid = "";
      //  public SalString __lsObjversion = "";
        public SalString __sObjstate = "";
        public SalString __sObjevents = "";
        public SalString __lsAttr = "";
        public SalString __lsResult = "";
        public SalString __sAction = "";
        public SalNumber __resCode;
        private static bool? _isRemote;
        private static BatchExecuteRequest executeRequest;
        private static RemoteProxy proxy = new RemoteProxy();
        private static BatchQuaryRequest quaryRequest = new BatchQuaryRequest();
        private static int Key = 100;
        public static bool IsRemote
        {
            get
            {
                if (_isRemote != null) return _isRemote.Value;

                _isRemote = Config.GetMutilConfig<Boolean>(false, "Fcdbas.Core.IsRemote", "IsRemote");

                return _isRemote.Value;
            }
        }
        public override int FindCount(IEntity Entity, SalString where)
        {
           
            if (Entity == null)
                return 0;
            if (IsRemote)
            {
                SqlQueryPackage spk = new SqlQueryPackage();
                spk.EntityType = Entity.GetType().FullName;
                spk.WhereClause = where;
                ScalarResult result = proxy.SelectCount(spk);
                if (result.Success)
                {
                     RecordCount= Convert.ToInt32(result.Result);
                }
                else
                    return 0;
            }
            else
            {
                Type[] tps = new Type[5];
                for (int i = 0; i < 5; i++)
                {
                    if (i < 3)
                        tps[i] = typeof(string);
                    if (i >= 3)
                        tps[i] = typeof(Int32);
                }
                //Entity<IEntity>.FindAll();
                MethodInfoX method = MethodInfoX.Create(Entity.GetType(), "FindCount", tps);
                object count = method.Invoke(method, where, "", "", 0, 0);
                RecordCount = Convert.ToInt32(count);
            }
            RecordPos = 0;
            if (this.EntityList != null && this.EntityList.Count > 0)
                this.EntityList.Clear();
            return RecordCount;
            
        }
        /// <summary>
        /// 准备要执行的查询
        /// </summary>
        /// <param name="dsName">数据源名称</param>
        /// <param name="typeName">实体类型全称FullName</param>
        /// <param name="where">where条件</param>
        /// <param name="fields"></param>
        /// <param name="orderby"></param>
        /// <param name="startRow">开始位置，0表示所有</param>
        /// <param name="maxRow">结束位置，0表示所有</param>
        public static void PrepareQueryBlock(string dsName,string typeName, SalString where, SalString fields, SalString orderby, int startRow, int maxRow)
        {
            if (quaryRequest == null)
                quaryRequest = new BatchQuaryRequest();
            if (quaryRequest.SqlStatements == null)
                quaryRequest.SqlStatements = new List<SqlQueryPackage>();
            SqlQueryPackage sp = new SqlQueryPackage();
            sp.DataSourceName = dsName;
            sp.WhereClause = where;
            sp.EntityType = typeName;
            sp.OrderByClause = orderby;
            sp.Fields = fields;
            sp.MaximumRow = maxRow;
            sp.StartRowIndex = startRow;
            quaryRequest.SqlStatements.Add(sp);
        }
        public static QuaryResult BatchQuery()
        {
            if (quaryRequest == null || quaryRequest.SqlStatements == null || quaryRequest.SqlStatements.Count == 0)
                return null;
            return proxy.BatchQuary(quaryRequest);
        }
        /// <summary>
        /// 批量查询，返回数据集列表
        /// </summary>
        /// <param name="DicResult">返回的结果列表，数据源+列表</param>
        /// <returns>成功返回true，失败返回false,用getlasterror取得失败的原因</returns>
        public static bool BatchQuery(Dictionary<string, IEntityList> DicResult)
        {
            if (DicResult == null)
                DicResult = new Dictionary<string, IEntityList>();
            QuaryResult result = BatchQuery();
            if (!result.Success)
            {
                sErrorMsg = result.Message;
                return false;
            }
            else
            {
                if (result.ResultList != null)
                {
                    foreach (DataContract.ObjectResult obj in result.ResultList)
                    {
                        IEntityList list = null;
                        if (obj.IsCompress && obj.Data != null)
                        {
                            byte[] data = obj.Data.Decompress();
                            list = Fcdbas.Core.Util.ObjectHelper.DeserialzieObject(data) as IEntityList;
                        }
                        else
                            list = obj.EntityList;
                        DicResult.Add(obj.DataSourceName, list);
                    }
                }
            }
            return true;
        }
        /// <summary>
        /// 准备要执行的语句
        /// </summary>
        /// <param name="sSql">要执行的语句</param>
        /// <param name="parms">参数</param>
        /// <param name="type"></param>
        /// <returns>返回键值，一般有关联关系的才需要使用</returns>
        public static int  PrepareSQLBlock(string sSql, Dictionary<string, object> parms, CommandType type = CommandType.StoredProcedure)
        {
            if (executeRequest == null)
                executeRequest = new BatchExecuteRequest();
            if (executeRequest.SqlStatements == null)
                executeRequest.SqlStatements = new List<SqlExecutePackage>();
            SqlExecutePackage pkg = new SqlExecutePackage();
            Key++;
            pkg.Statement = sSql;
            pkg.SqlParams = parms;
            pkg.ParamType = SqlParamType.Dictionary;
            pkg.ExecuteType = type;
            pkg.Key = Key;
            pkg.DoAction = "DO";
            executeRequest.SqlStatements.Add(pkg);
            return Key;
        }
        /// <summary>
        /// 远程直接执行一个语句
        /// </summary>
        /// <param name="sSql">要执行的语句</param>
        /// <param name="parms">参数</param>
        /// <param name="type">存储过程还是DDL</param>
        /// <returns>成功返回true，失败用GetLastError取得失败的原因</returns>
        public static bool RemoteSQLExecute(string sSql, Dictionary<string, object> parms, CommandType type = CommandType.StoredProcedure)
        {
            PrepareSQLBlock(sSql, parms, type);
            ExecuteResult result = null;
            try
            {
                result = proxy.BatchExecute(executeRequest);
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
                sErrorMsg = ex.Message;
                return false;
            }
            finally
            {
                executeRequest.SqlStatements.Clear();
            }
            if (result.Success)
            {
                if (result.ResultPackages != null && result.ResultPackages.Count > 0)
                {
                    parms = result.ResultPackages[0].SqlParams;
                }
                return true;
            }
            else
            {
                sErrorMsg = result.Message;
                
                return false;
            }
        }
        /// <summary>
        /// 远程直接执行一个语句
        /// </summary>
        /// <param name="entity">对象</param>
        /// <param name="sSql">要执行的语句</param>
        /// <param name="parms">参数</param>
        /// <param name="type">存储过程还是DDL</param>
        /// <returns>成功返回true，失败用GetLastError取得失败的原因</returns>
        public static bool RemoteSQLExecute(IEntity entity, string sSql, CommandType type = CommandType.StoredProcedure)
        {
            PrepareSQLBlock(entity,sSql,false,false,null, type);
            ExecuteResult result = null;
            try
            {
                result = proxy.BatchExecute(executeRequest);
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
                sErrorMsg = ex.Message;
                return false;
            }
            finally
            {
                executeRequest.SqlStatements.Clear();
            }
            if (result.Success)
            {
                if (result.ResultPackages != null && result.ResultPackages.Count > 0)
                {
                    ExecuteResultPackage erp = result.ResultPackages[0];
                    if (erp.ParamType == SqlParamType.Entity && erp.ParamData != null)
                    {
                        IEntity en = Fcdbas.Core.Util.ObjectHelper.DeserialzieObject(erp.ParamData) as IEntity;
                        entity.CopyFrom(en);
                        entity.Dirtys.Clear();
                        entity.ClearAdditionalValues();
                    }
                }
                return true;
            }
            else
            {
                sErrorMsg = result.Message;

                return false;
            }
        }
        /// <summary>
        /// 批量准备，主要是是针对上下文记录有关联关系的。如果没有关联关系的，传入前面二个参数即可。
        /// </summary>
        /// <param name="Entity">实体对象</param>
        /// <param name="sSql">语句</param>
        /// <param name="IsStandard">是否执行标准语句，指的是__NEW，__MODIFY</param>
        /// <param name="IsFirst">是否先执行,可省略</param>
        /// <param name="association">关联的语句可省略</param>
        /// <param name="type">执行的类型可省略</param>
        /// <param name="KeyRef">关联的键值</param>
        /// <param name="doAction">动作</param>
        /// <returns>返回的键值</returns>
        public static int PrepareSQLBlock(IEntity Entity, string sSql, bool IsStandard = true, bool IsFirst = false, Dictionary<string, string> association = null, CommandType type = CommandType.StoredProcedure, int KeyRef = 0,string doAction = "DO")
        {
            if (executeRequest == null)
                executeRequest = new BatchExecuteRequest();
            if (executeRequest.SqlStatements == null)
                executeRequest.SqlStatements = new List<SqlExecutePackage>();
            SqlExecutePackage pkg = new SqlExecutePackage();
            Key++;
            pkg.Statement = sSql;
            pkg.Key = Key;
            pkg.Entity = Entity;
            pkg.RefKey = KeyRef;
            pkg.ParamType = SqlParamType.Entity;
            pkg.EntityType = Entity.GetType().FullName;
            pkg.ParamData = Fcdbas.Core.Util.ObjectHelper.SerialzieObject(Entity);
            pkg.ExecuteType = type;
            pkg.IsStandard = IsFirst;
            pkg.DoAction = doAction;
            pkg.IsStandard = IsStandard;
            pkg.Association = association;
            executeRequest.SqlStatements.Add(pkg);
            return Key;
        }
        private IEntityList GetDataFromRemote(string typeName, SalString where, SalString orderby, SalString fields, int startRow, int maxRow)
        {
            BatchQuaryRequest request = new BatchQuaryRequest();
            request.SqlStatements = new List<SqlQueryPackage>();
            SqlQueryPackage sp = new SqlQueryPackage();
            sp.WhereClause = where;
            sp.OrderByClause = orderby;
            sp.Fields = fields;
            sp.MaximumRow = maxRow;
            sp.EntityType = typeName;
            sp.StartRowIndex = startRow;
            request.SqlStatements.Add(sp);
            QuaryResult result = proxy.BatchQuary(request);
            if (result.Success)
            {
                if (result.ResultList != null && result.ResultList.Count > 0)
                {
                    if (result.ResultList[0].IsCompress && result.ResultList[0].Data != null)
                    {
                        byte[] data = result.ResultList[0].Data.Decompress();
                        return Fcdbas.Core.Util.ObjectHelper.DeserialzieObject(data) as IEntityList;
                    }
                    else
                        return result.ResultList[0].EntityList;
                }
                else
                    return null;
            }
            else
            {
                translate.ShowMessage(result.Message, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                return null;
            }
        }
        /// <summary>
        /// 根据条件取得数据实体列表
        /// </summary>
        /// <param name="where"></param>
        /// <param name="orderby"></param>
        /// <param name="mode">抽取模式,1抽取下一段,2抽取所有,3重新抽取,4刷新当前记录</param>
        /// <returns></returns>
        public IEntityList FindFromRemote(IEntity Entity, SalString where, SalString fields, SalString orderby, int mode, int RecordLimit)
        {
            //我刚才给你的备份,里面有一个Funciton: FndVpdPolicy_GetPolicy, 这个是你Call所有的视图的时候, 都需要调用下,返回字符串,是额外需要合并在一起的Where条件
            //如果为null或者'',就不用管
            if (Entity == null)
            {
                Fcdbas.Core.Log.XTrace.WriteLine(string.Format("Find Entity is null"));
                return null;
            }
            
            Fcdbas.Core.Log.XTrace.WriteLine(string.Format("执行查询，对象类型是：{0},where 条件是：{1},字段：{2},模式：{3},orderby:{4}", Entity.GetType().ToString(), where, fields, mode, orderby));
            object res = null;
            if (mode == 4 && Entity["objid"] != null)
            {
                where = "objid = '" + Entity["objid"].ToString() + "'";

                IEntityList list1 = GetDataFromRemote(Entity.GetType().FullName, where, orderby, fields, 0, 0);
                if (list1 == null || list1.Count == 0)
                    return EntityList;
                if (EntityList == null || EntityList.Count == 0)
                {
                    EntityList = list1;
                    return EntityList;
                }
                IEntity enN = list1[0];
                IEntity enO = EntityList.Find("objid", Entity["objid"]);
                enO.CopyFrom(enN);
                return EntityList;
            }
            //Entity<IEntity>.FindAll();
            switch (mode)
            {
                case 3:
                    if (RecordCount >= RecordLimit)
                    {
                        res = GetDataFromRemote(Entity.GetType().FullName, where, orderby, fields, 0, RecordLimit);
                        RecordPos = RecordLimit;
                    }
                    else
                    {
                        res = GetDataFromRemote(Entity.GetType().FullName, where, orderby, fields, 0, 0);
                        RecordPos = 0;
                    }
                    EntityList = res as IEntityList;
                    break;
                case 1:
                    IEntityList list;
                    if (RecordCount >= RecordPos + RecordLimit)
                        list = GetDataFromRemote(Entity.GetType().FullName, where, orderby, fields, RecordPos, RecordLimit);
                    else
                    {
                        int nCount = RecordCount - RecordPos;
                        if (nCount <= 0)
                            return EntityList;
                        list = GetDataFromRemote(Entity.GetType().FullName, where, orderby, fields, RecordPos, nCount);
                    }

                    RecordPos = RecordPos + RecordLimit;
                    if (this.EntityList == null)
                    {
                        this.EntityList = list;
                    }
                    else
                    {
                        foreach (var en in list)
                        {
                            EntityList.Add(en);
                        }
                    }
                    // EntityList = res as IEntityList;

                    break;
                case 2:
                    res = GetDataFromRemote(Entity.GetType().FullName, where, orderby, fields, 0, 0);

                    EntityList = res as IEntityList;

                    break;
            }

            return EntityList;
        }
        /// <summary>
        /// 批量执行，跟PrepareSQLBlock函数对应
        /// </summary>
        /// <returns>执行的结果</returns>
        public static ExecuteResult BatchExecute()
        {
            ExecuteResult result = null;
            try
            {
                result = proxy.BatchExecute(executeRequest);
                
            }
            catch (Exception ex)
            {
                Fcdbas.Core.Log.XTrace.WriteException(ex);
                executeRequest.SqlStatements.Clear();
                sErrorMsg = ex.Message;
                Key = 100;
                return result;
            }

            if (result.Success)
            {
                if (result.ResultPackages != null && executeRequest.SqlStatements != null)
                {
                    for (int i = 0; i < executeRequest.SqlStatements.Count; i++)
                    {
                        SqlExecutePackage pkg = executeRequest.SqlStatements[i];
                        if (pkg.ParamType != SqlParamType.Entity)
                            continue;
                        if (pkg.DoAction == "CHECK")
                            continue;
                        pkg.Entity.Dirtys.Clear();
                        pkg.Entity.ClearAdditionalValues();
                        var erp = result.ResultPackages.Find(p => p.Key == pkg.Key);
                        if (erp != null)
                        {
                            if (erp.ParamType == SqlParamType.Entity && erp.ParamData != null)
                            {
                                IEntity en = Fcdbas.Core.Util.ObjectHelper.DeserialzieObject(erp.ParamData) as IEntity;
                                pkg.Entity.CopyFrom(en);
                                pkg.Entity.Dirtys.Clear();
                                pkg.Entity.ClearAdditionalValues();
                                if (pkg.Entity.Status != RecordStatus.Delete && pkg.DoAction == "DO")
                                    pkg.Entity.Status = RecordStatus.Normal;
                            }
                        }
                    }
                }
            }
            else
            {
                sErrorMsg = result.Message;
            }
            executeRequest.SqlStatements.Clear();
            Key = 100;
            return result;
        }
        public static WinTranslate translate = WinTranslate.GetTranslate();
        private static DAL _dal;
        public static DAL dal
        {
            get
            {
                if (_dal == null)
                    _dal = DAL.Create();
                return _dal;
            }
        }
        internal static SalString GetProcedureName(SalString sSql)
        {
            int idx = -1;
            string sql = sSql;
            idx = sql.IndexOf(":=");
            if (idx > 0)
            {
                sql = sql.Substring(idx + 2, sql.Length - idx -2).Trim();
            }
            int lIdx = sql.IndexOf("(");
            if (lIdx > 0)
                return sql.Substring(0, lIdx).Trim();
            else
                return "";
        }
        internal static SalString GetFunctionName(SalString sSql)
        {
            int idx = -1;
            string sql = sSql;
            if (sql.StartsWith("Select", StringComparison.OrdinalIgnoreCase))
            {
                idx = sql.IndexOf("Select", StringComparison.OrdinalIgnoreCase);
                if(idx >= 0)
                    sql = sql.Substring(idx + 6,sql.Length - idx -6).Trim();
            }
           
            int lIdx = sql.IndexOf("(");
            if (lIdx >= 0)
                return sql.Substring(0, lIdx);
            else
                return "";
        }
        public cSessionManager(object derived)
        {
            this._derived = derived;
            executeRequest = new BatchExecuteRequest();
        }
        internal SalBoolean DbSQLBlock(IEntity Entity, SalString sSql,bool standard =true)
        {
            string procedure = GetProcedureName(sSql);
            if (dal.DbType == DatabaseType.MySql)
                procedure = procedure.Replace(".", "_");
            if (!Security.IsMethodAvaliable(AppEnvironment.Session.USER_ID, procedure))
            {
                translate.ShowMessage("没有执行存储过程[%%1]的权限，请联系系统管理员。", procedure);
                return false;
            }
            if (standard)
                return DbPLSQLBlock(Entity, sSql);
            else
            {
                SalBoolean res = DbMySQLBlock(Entity, sSql);
                this.__lsResult = Entity.Result;
                return res;
            }
        }
        public SalBoolean DbPLSQLBlock(IEntity Entity,SalString sSql)
        {
            Dictionary<SalString, object> dic = BuildParameter(Entity);
            if (Entity["objversion"] != null)
                Entity.OldObjVersion = Entity["objversion"].ToString();
            //SalBoolean res = DbMySQLBlock(Entity, sSql, dic);
            SalBoolean res = DbMySQLBlock(sSql, dic);
            if (!res)
            {
                SalString msg = "";
                this.ErrorCode = GetSqlLastError(ref msg);
                this.ErrorMsg = msg;
            }
            else
            {
                this.ErrorCode = 0;
                this.ErrorMsg = "";
            }
            if(dic.ContainsKey("attr_"))
             this.__lsAttr = dic["attr_"].ToString();
            if (dic.ContainsKey("objversion_") && res)
                Entity["objversion"] = dic["objversion_"];
            if (dic.ContainsKey("info_"))
                this.__lsResult = dic["info_"].ToString();
            if (dic.ContainsKey("objid_") && res)
                Entity["objid"] = dic["objid_"];
            return res;
        }
        private Dictionary<SalString, object> BuildParameter(IEntity entity)
        {
            Dictionary<SalString, object> dic = new Dictionary<SalString, object>();
            dic.Add("info_", __lsResult);
            if (entity["objid"] != null)
                dic.Add("objid_", entity["objid"].ToString());
            else
                dic.Add("objid_", "");
            if (entity["objversion"] != null)
                //dic.Add("objversion_", ((DateTime)entity["objversion"]).ToString("yyyy-MM-dd HH:mm:ss"));
                dic.Add("objversion_", entity["objversion"].ToString());
            else
                dic.Add("objversion_", "");
           
            dic.Add("attr_", __lsAttr);
            dic.Add("action_", __sAction);
            return dic;
        }
        public static List<Fcdbas.Biz.fnd_enumerate> Enumerates = null;
        /// <summary>
        /// 返回enums的数据
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<string> GetEnums(IEntity entity,string key)
        {
            
            string enums = "";
            if (Enumerates == null)
            {
                string conName = fnd_enumerate.Meta.ConnName;
                fnd_enumerate.Meta.ConnName = FndDAL.SQLite;
               
                Enumerates = fnd_enumerate.FindAll();
                fnd_enumerate.Meta.ConnName = conName;
            }
            
            //修改用本地缓存的方式处理
            /*
           // this.DbTransactionBegin(entity);
            if (cSessionManager.IsRemote)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                dic.Add("client_values_", "");
                dic.Add("lu_name_", key);
                if(RemoteSQLExecute("EnumerateSys_Enumerate(:client_values_,:lu_name_)", dic))
                    enums = dic["client_values_"].ToString();
            }
            else
            {
                Dictionary<SalString, object> dic = new Dictionary<SalString, object>();
                dic.Add("client_values_", "");
                dic.Add("lu_name_", key);
                this.DbMySQLBlock(entity, "EnumerateSys_Enumerate(:client_values_,:lu_name_)", dic);
                enums = dic["client_values_"].ToString();
            }
             * */
            fnd_enumerate fenum = Enumerates.Find(p => p.lu_name == key);
            if (fenum != null)
            {
                enums = fenum.client_value;
            }
            string[] es = enums.Split("^");
            
           // this.DbTransactionClear(entity);
            return es.ToList();

        }
        public SalBoolean HandleSqlWarnings(SalString sResult)
        {
            if (string.IsNullOrEmpty(sResult))
                return true;
            if (translate.ShowMessage(sResult, "", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
                return true;
            else
                return false;
            //SalArray<SalString> salArray = new SalArray<SalString>();
            //SalArray<SalString> salArray2 = new SalArray<SalString>();
            //SalNumber x = 0;
            //SalString salString = "";
            ////Var.Console.TextAdd(0, "HandleSqlWarnings( '" + sResult + "' )");
            //sResult.Tokenize("", EntityBase.Record_Separator, salArray);
            //while (salArray[new int[]
            //{
            //    x
            //}] != "")
            //{
            //    salArray[new int[]
            //    {
            //        x
            //    }].Tokenize("", EntityBase.Field_Separator, salArray2);
            //    SalArray<SalString> arg_A5_0 = salArray2;
            //    int[] indices = new int[1];
            //    if (arg_A5_0[indices] == "WARNING")
            //    {
            //        if (salString == "")
            //        {
            //            salString = salArray2[new int[]
            //            {
            //                1
            //            }];
            //        }
            //        else
            //        {
            //            salString = salString + "\r\n" + salArray2[new int[]
            //            {
            //                1
            //            }];
            //        }
            //    }
            //    x += 1;
            //}
            //if (salString != "")
            //{
            //    translate.ShowMessage(salString);
            //    //Sal.MessageBeep(0);
            //    //switch (Int.PalMessageBox(salString, Resources.CAPTION_Warning, 49))
            //    ////{
            //    //    case 1:
            //    //        return true;
            //    //    case 2:
            //    //        return false;
            //    //}
            //}
           // return true;
        }
        public SalNumber _SetAction(SalString sAction)
        {
            this.__sAction = sAction;
            //Var.Console.TextAdd(0, "Action = '" + this.__sAction + "'");
            return 0;
        }
        public SalBoolean HandleSqlResult(SalString sResult)
        {
            SalArray<SalString> salArray = new SalArray<SalString>();
            SalArray<SalString> salArray2 = new SalArray<SalString>();
            SalNumber x = 0;
            //Var.Console.TextAdd(0, "HandleSqlResult( '" + sResult + "' )");
            sResult.Tokenize("", EntityBase.Record_Separator, salArray);
            while (salArray[new int[]
			{
				x
			}] != "")
            {
                salArray[new int[]
				{
					x
				}].Tokenize("", EntityBase.Field_Separator, salArray2);
                SalArray<SalString> arg_97_0 = salArray2;
                int[] indices = new int[1];
                if (arg_97_0[indices] == "INFO")
                {
                   // Sal.MessageBeep(0);
                    translate.ShowMessage(salArray2[new int[]
                    {
                        1
                    }]);
                    //Int.PalMessageBox(salArray2[new int[]
                    //{
                    //    1
                    //}], Resources.CAPTION_Information, 64);
                }
                x += 1;
            }
            return true;
        }
        /// <summary>
        /// 开始一个事务
        /// </summary>
        /// <param name="sSql"></param>
        /// <returns></returns>
        public static SalBoolean DbTransactionBegin()
        {
            return dal.BeginTransaction();
        }
        /// <summary>
        /// 回滚当前事务
        /// </summary>
        /// <returns></returns>
        public static SalBoolean DbTransactionClear()
        {
            Int32 res = dal.Rollback();
            if (res == 0)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 提交当前事务
        /// </summary>
        /// <returns></returns>
        public static SalBoolean DbTransactionEnd()
        {
            Int32 res = dal.Commit();
            if (res == 0)
                return true;
            else
                return false;
        }
        private static SalNumber nErrorCode;
        private static SalString sErrorMsg;
        public static SalNumber GetSqlLastError(ref SalString msg)
        {
            msg = sErrorMsg;
            return nErrorCode;
        }
        public static SalString GetSqlLastError()
        {
            return sErrorMsg;
        }
        public static SalString GetUserFunctionValue(SalString function)
        {
            
           // DbTransactionBegin();
            if (IsRemote)
            {
                return RemoteExecuteScalar<SalString>(function);
            }
            else
            {
                string func = GetFunctionName(function);
                if (!Security.IsFunctionAvaliable(AppEnvironment.Session.USER_ID, func))
                {
                    translate.ShowMessage("没有执行函数[%%1]的权限，请联系系统管理员。", function);
                    return "";
                }
                string res = dal.ExecuteScalar<string>(function);
                //DbTransactionEnd();

                return res;
            }
        }
        public static T RemoteExecuteScalar<T>(string sSql)
        {
            SqlQuaryRequest request = new SqlQuaryRequest();
            request.SqlStatement = sSql;
            request.ResultType = typeof(T).FullName;
            ScalarResult result = proxy.ExecuteScalar(request);
            if (result.Success)
            {
                
                return (T)Convert.ChangeType(result.Result, typeof(T));
            }
            else
            {
                translate.ShowMessage(result.Message,"",System.Windows.Forms.MessageBoxButtons.OK,System.Windows.Forms.MessageBoxIcon.Error);
                return default(T);

            }
        }
        /// <summary>
        /// 执行函数，返回函数的内容
        /// </summary>
        /// <typeparam name="T">返回的类型</typeparam>
        /// <param name="function">要执行的函数</param>
        /// <param name="bCheck">是否检查有无权限</param>
        /// <returns></returns>
        public static T GetUserFunctionValue<T>(SalString function,bool bCheck=true)
        {
            if (IsRemote)
            {

                return RemoteExecuteScalar<T>(function);
            }
            else
            {
                if (bCheck)
                {
                    string func = GetFunctionName(function);
                    if (!Security.IsFunctionAvaliable(AppEnvironment.Session.USER_ID, func))
                    {
                        translate.ShowMessage("没有执行函数[%%1]的权限，请联系系统管理员。", function);
                        return default(T);
                    }
                }
                // DbTransactionBegin();
                return dal.ExecuteScalar<T>(function);
            }
            //DbTransactionEnd();
        }
        /// <summary>
        /// 调用存储过程或者函数,不会自动提交, 可能多个Block一起执行， 一般会和DbTransactionBegin一起使用
        /// </summary>
        /// <param name="sSql">SQL格式为：Result := StoredProcessdure(:Name,:Id)</param>
        /// <returns></returns>
        public static SalNumber DbMySQLBlock(SalString sSql, Dictionary<SalString, object> parms, CommandType type = CommandType.StoredProcedure)
        {
            Int32 res = 0;// Fcdbas.Biz.fnd_table_defined.Meta.Execute(sSql, parms, type);
            sErrorMsg = "";
            nErrorCode = 0;
            res= dal.Execute(sSql, parms, type);
            if (res == -1)
            {
                string msg = "";
                nErrorCode = dal.GetSqlException(ref msg);
                sErrorMsg = msg;

            }
            // return res;
            if (res >= 0)
                return true;
            else
                return false;
           
        }
        public static SalNumber DbMySQLBlock(string sSql, Dictionary<string, object> parms, CommandType type = CommandType.StoredProcedure)
        {
            Int32 res = 0;// Fcdbas.Biz.fnd_table_defined.Meta.Execute(sSql, parms, type);
            sErrorMsg = "";
            nErrorCode = 0;
            res = dal.Execute(sSql, parms, type);
            if (res == -1)
            {
                string msg = "";
                nErrorCode = dal.GetSqlException(ref msg);
                sErrorMsg = msg;

            }
            // return res;
            if (res >= 0)
                return true;
            else
                return false;

        }
        

        /// <summary>
        /// 调用存储过程或者函数,自动提交
        /// </summary>
        /// <param name="sSql">SQL格式为：Result := StoredProcessdure(:Name,:Id)</param>
        /// <returns></returns>
        public static SalBoolean DbMySQLTransaction(SalString sSql, Dictionary<SalString, object> parms, CommandType type = CommandType.StoredProcedure)
        {
            DbTransactionBegin();
            SalBoolean res = DbMySQLBlock(sSql, parms, type);
            SalBoolean r = false;
            if (res)
                r = Fcdbas.Biz.fnd_table_defined.Meta.Commit();
            else
                r = Fcdbas.Biz.fnd_table_defined.Meta.Rollback();
            return r;
        }
        public SalBoolean StoreSqlResult(SalString sResult)
        {
            if (string.IsNullOrEmpty(sResult))
                return true;
            translate.ShowMessage(sResult, "", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
            return false;
            //SalArray<SalString> salArray = new SalArray<SalString>();
            //SalArray<SalString> salArray2 = new SalArray<SalString>();
            //SalNumber x = 0;
            ////Var.Console.TextAdd(0, "StoreSqlResult( '" + sResult + "' )");
            //sResult.Tokenize("", EntityBase.Field_Separator, salArray);
            //while (salArray[new int[]
            //{
            //    x
            //}] != "")
            //{
            //    salArray[new int[]
            //    {
            //        x
            //    }].Tokenize("", EntityBase.Record_Separator, salArray2);
            //    SalArray<SalString> arg_97_0 = salArray2;
            //    int[] indices = new int[1];
            //    if (arg_97_0[indices] == "INFO")
            //    {
            //        cSessionManager.__c_sSqlResult[new int[]
            //        {
            //            Int.PalArrayCount(cSessionManager.__c_sSqlResult)
            //        }] = salArray2[new int[]
            //        {
            //            1
            //        }];
            //    }
            //    x += 1;
            //}
           // return true;
        }
    }
}
